﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;
using UFIDA.U9.SM.Ship;
using UFIDA.U9.PM.PO;
using UFSoft.UBF.PL;
using UFIDA.U9.PM.Rcv;
using UFIDA.U9.SM.RMA;
using UFIDA.U9.SM.SO;
using UFIDA.U9.CBO.SCM.Customer;
using UFIDA.U9.CBO.MFG.BOM;
using UFIDA.U9.AAI.TransEntry;
using UFIDA.U9.CBO.FI.VoucherCategory;
using UFIDA.U9.CBO.SCM.Node;
using UFSoft.UBF.Util.DataAccess;


namespace UFIDA.U9.Cust.LS.PlugBE
{
    /// <summary>
    /// 玖源机械项目
    /// 交易分录
    /// 久源机械凭证类型启用了记账、银行、票据、现金等凭证类型，
    /// 现需根据收款单、付款单的结算方式修改交易分录的凭证类型
    /// </summary>
    class JYJXAAIExtend : IEventSubscriber
    {
        //配置XX.sub.xml文件放置到portal/bin下，dll文件放置到portal/ApplicationServer/Libs下
        public void Notify(params object[] args)
        {
            if (args != null && args.Length != 0 && args[0] is EntityEvent)
            {
                BusinessEntity.EntityKey key = ((EntityEvent)args[0]).EntityKey;

 
                TransEntryHead transEntryHead = key.GetEntity() as TransEntryHead;
                if (transEntryHead == null)
                    return;
         
                if (transEntryHead.DocType == "收款单" || transEntryHead.DocType == "付款单")
                {
                    string VoucherTypeCode = "";
                    foreach (var line in transEntryHead.TransactionEntrys)
                    {
                        //if (line.SettlementMethod is null) continue;
                        string SettStr = GetSettlementMethod(line.OriginalEntity, transEntryHead.DocType);
                        if (SettStr == "YZ01")// 现金
                        {
                            VoucherTypeCode = "07";
                        }
                        if (SettStr == "YZ02")// 现金凭证
                        {
                            VoucherTypeCode = "03";
                        }
                        if (SettStr == "YZ03")// 银行凭证
                        {
                            VoucherTypeCode = "05"; // 票据凭证
                        }
                    }
                    
                    if (!string.IsNullOrEmpty(VoucherTypeCode))
                    {
                        VoucherCategory cate=VoucherCategory.Finder.Find($"Code={VoucherTypeCode}");
                        if (cate == null)
                        {
                            throw new Exception($"凭证类型[{VoucherTypeCode}]查找失败!");
                        }
                        //using (ISession session = Session.Open())
                        //{

                        //    transEntryHead.VoucherType = cate;
                        //    session.Modify( transEntryHead );
                        //    session.Commit();
                        //}
                        string sql = $"UPDATE AAI_TransEntryHead set VoucherType= {cate.ID}WHERE DocNumber ='{transEntryHead.DocNumber}'";
                        DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out object seetType);
                    }

                   
                }
            }
        }




        /// <summary>
        /// 根据BuissType类型获取付款单或者收款单的结算方式
        /// </summary>
        /// <returns></returns>
        /// <summary>
        /// 根据业务类型获取付款单或收款单的结算方式代码
        /// </summary>
        /// <param name="settlementId">单据行ID</param>
        /// <param name="businessType">业务类型("付款单"或"收款单")</param>
        /// <returns>结算方式代码</returns>
        private static string GetSettlementMethod(long settlementId, string businessType)
        {
            // 参数验证
            if (string.IsNullOrWhiteSpace(businessType))
                throw new ArgumentNullException(nameof(businessType), "业务类型不能为空");

            // 确定查询参数
            string tableName, entityType;
            switch (businessType)
            {
                case "付款单":
                    tableName = "AP_PayBillLine";
                    entityType = "UFIDA.U9.AP.Payment.PayBillLine";
                    break;
                case "收款单":
                    tableName = "AR_RecBillLine";
                    entityType = "UFIDA.U9.AR.Receival.RecBillLine";
                    break;
                default:
                    throw new ArgumentException("无效的业务类型，只支持'付款单'或'收款单'", nameof(businessType));
            }

            
                object seetType=null;

                // 使用参数化查询
                string sql = $@"
            SELECT sett.Code 
            FROM AAI_TransactionEntry line 
            LEFT JOIN AAI_TransEntryHead head ON head.id = line.TransEntryHead 
            LEFT JOIN {tableName} payl ON payl.id = line.OriginalEntity
            LEFT JOIN CBO_SettlementMethod sett ON sett.id = payl.SettlementMethod 
            WHERE payl.id = {settlementId} 
            AND OriginalEntityType = '{entityType}'";

            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out seetType);

            if (seetType == null)
                return "";
            else
             return seetType.ToString();
        }
             
        } 


    }
  
